package com.socket.nio.nio.sticky.delimiterbased;

import com.socket.nio.nio.constant.NioConstant;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;

/**
 * 分隔符解码器： 以固定的分隔符对消息进行解码
 *
 * @author Hexudong
 * @date 2025/5/5
 */
public class DelimiterServer {

  private final int port;

  public DelimiterServer(int port) {
    this.port = port;
  }

  public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      ServerBootstrap s = new ServerBootstrap();
      s.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
              // 创建分隔符ByteBuf
              ByteBuf delimiter = Unpooled.copiedBuffer(NioConstant.DELIMITER, CharsetUtil.UTF_8);

              ChannelPipeline pipeline = ch.pipeline();
              pipeline.addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
              // 将 ByteBuf -> String
              pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
              pipeline.addLast(new DelimiterServerHandler());
            }
          });
      ChannelFuture f = s.bind(port).sync();
      System.out.println("DelimiterServer started on port " + port);
      f.channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }

  public static void main(String[] args) throws Exception {
    new DelimiterServer(8082).run();
  }
}
